package com.yuan.order.controller;

import com.google.common.collect.Lists;

import com.yuan.order.dataobject.ProductCategory;
import com.yuan.order.dataobject.ProductInfo;
import com.yuan.order.service.ProductCategoryService;
import com.yuan.order.service.ProductInfoService;
import com.yuan.order.service.impl.ProductCategoryServiceImpl;
import com.yuan.order.service.impl.ProductInfoServiceImpl;
import com.yuan.order.utils.ResultVOUtils;
import com.yuan.order.vo.ProductInfoVO;
import com.yuan.order.vo.ProductVO;
import com.yuan.order.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 买家商品API
 *
 * @Author yuan
 * @Date 2021/2/25 9:40
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("/list")
    @Cacheable(cacheNames = "product",key = "123")
    public ResultVO list() {
        //1.查询所有上架商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        //2.查询商品类别
        //传统方式
        /*List<Integer> categoryIdList = new ArrayList<>();
        for (ProductInfo productInfo:productInfoList){
            categoryIdList.add(productInfo.getCategoryType());
        }*/
        //lambda
        List<Integer> categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(categoryTypeList);
        //3.数据拼装
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList) {
                if (productCategory.getCategoryType().equals(productInfo.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultVOUtils.success(productVOList);
    }
}
